<template>
  <j-modal
    :width='1200'
    :visible='visible'
    :title='title'
    switchFullscreen
    @ok='handleSubmit'
    @cancel='close'
    style='top:50px;'
    cancelText='关闭'
  >
    <a-tabs :active-key='activeKey' @tabClick='tabClick'>
      <a-tab-pane key='role' tab='角色'>
        <a-spin tip='Loading...' :spinning='false'>
          <a-row :gutter='10' style='padding: 10px; margin: -10px' v-if='visible'>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-form layout='inline' @keyup.enter.native='searchQuery'>
                  <a-row :gutter='24'>
                    <a-col :md='7' :sm='24'>
                      <a-form-item>
                        <a-input placeholder='角色编号' v-model='queryParam.roleCode'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-form-item>
                        <a-input placeholder='角色名称' v-model='queryParam.roleName'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-button type='primary' @click='searchQuery' icon='search' style='margin-top: 5px'>查询</a-button>
                    </a-col>
                  </a-row>
                </a-form>
                <a-table
                  ref='table'
                  size='small'
                  bordered
                  :scroll="{
                      x:'max-content'
                    }"
                  tableLayout='auto'
                  rowKey='roleCode'
                  :columns='rolesColumns'
                  :dataSource='roles'
                  :pagination='ipagination'
                  :loading='loading'
                  :customRow="onClickRow"
                  :rowSelection='{selectedRowKeys: roleSelectedRowKeys, onSelect: onSelect,onSelectAll:onSelectAll}'
                  @change='handleTableChange'
                >
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                </a-table>

              </a-card>
            </a-col>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-table
                  ref='table'
                  size='small'
                  bordered
                  :scroll="{
                     x:'max-content'
                  }"
                  tableLayout='auto'
                  rowKey='roleCode'
                  :columns='rolesColumns'
                  :dataSource='rolesData'
                >
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                  <template slot='action' slot-scope='text, record, index'>
                    <a @click='handleDelete(record)'>删除</a>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
      </a-tab-pane>

      <a-tab-pane key='position' tab='职位'>
        <a-spin tip='Loading...' :spinning='false'>
          <a-row :gutter='10' style='padding: 10px; margin: -10px' v-if='visible'>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-form layout='inline' @keyup.enter.native='searchQuery'>
                  <a-row :gutter='24'>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='职位编号' v-model='queryParam.positionCode'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='职位名称' v-model='queryParam.positionName'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-button type='primary' @click='searchQuery' icon='search' style='margin-top: 5px'>查询</a-button>
                    </a-col>
                  </a-row>
                </a-form>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                    x:'max-content'
                  }"
                  tableLayout='auto'
                  rowKey='positionCode'
                  :columns='positionsColumns'
                  :dataSource='positions'
                  :pagination='ipagination'
                  :loading='loading'
                  :customRow="onClickRow"
                  :rowSelection='{selectedRowKeys: positionSelectedRowKeys,
                   onSelect: onSelect,onSelectAll:onSelectAll}'
                  @change='handleTableChange'
                >
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                </a-table>

              </a-card>
            </a-col>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                x:'max-content'
              }"
                  tableLayout='auto'
                  rowKey='positionCode'
                  :columns='positionsDataColumns'
                  :dataSource='positionsData'
                >

                  <template slot='mainPosition' slot-scope='text, record, index'>
                    <a-radio-group v-model='record.mainPosition' @change='onPositionChange(record,this)'>
                      <a-radio :value='0'>
                        主职
                      </a-radio>
                      <a-radio :value='1'>
                        副职
                      </a-radio>
                    </a-radio-group>
                  </template>
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                  <template slot='action' slot-scope='text, record, index'>
                    <a @click='handleDelete(record)'>删除</a>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
      </a-tab-pane>

    </a-tabs>

  </j-modal>

</template>

<script>
  import { filterObj } from '@/utils/util'
  import { queryDepartTreeList, getUserList, queryUserByDepId } from '@/api/api'
  import { getAction, postAction } from '@/api/manage'
  import JInput from '@/components/cn-form/JInput.vue'
  import { getStore } from '@/utils/storage'
  import { PageListMixin } from '@/mixins/PageListMixin'

  export default {
    name: 'ConfigRolePos',
    components: { JInput },
    props: {
      modalWidth: {
        default() {
          return '1200px'
        }
      },
      'multi': Boolean
    },
    data() {
      return {
        typeLoading: false,
        queryParam: {
          code: '',
          name: ''
        },

        positions: [],
        positionsData: [],
        positionsColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '职位编号',
            align: 'center',
            dataIndex: 'positionCode'
          },
          {
            title: '职位名称',
            align: 'center',
            dataIndex: 'positionName'
          },
          {
            title: '职位级别',
            align: 'center',
            dataIndex: 'positionLevel_dictText'
          }
        ],
        positionsDataColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '职位编号',
            align: 'center',
            dataIndex: 'positionCode'
          },
          {
            title: '职位名称',
            align: 'center',
            dataIndex: 'positionName'
          },
          {
            title: '职位级别',
            align: 'center',
            dataIndex: 'positionLevel_dictText'
          },
          {
            title: '职位类型',
            align: 'center',
            dataIndex: 'mainPosition',
            scopedSlots: { customRender: 'mainPosition' }
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            width: 80,
            ellipsis: true,
            scopedSlots: { customRender: 'action' }
          }
        ],

        roles: [],
        rolesData: [],
        rolesColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '角色编号',
            align: 'center',
            dataIndex: 'roleCode'
          },
          {
            title: '角色名称',
            align: 'center',
            dataIndex: 'roleName'
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            width: 80,
            ellipsis: true,
            scopedSlots: { customRender: 'action' }
          }
        ],
        rolesDataColumns: [
          {
            title: '#',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '角色编号',
            align: 'center',
            dataIndex: 'roleCode'
          },
          {
            title: '角色名称',
            align: 'center',
            dataIndex: 'roleName'
          },
          {
            title: '操作',
            align: 'center',
            dataIndex: 'action',
            width: 80,
            ellipsis: true,
            scopedSlots: { customRender: 'action' }
          }
        ],

        scrollTrigger: {},

        roleSelectedRowKeys: [],
        roleSelectionRows: [],

        positionSelectedRowKeys: [],
        positionSelectionRows: [],

        title: '用户配置',
        selectedKeys: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
        userInfo: this.$store.getters.userInfo,
        activeKey: 'role',
        url: {},
        record: null
      }
    },
    mixins: [PageListMixin],
    computed: {
      // 计算属性的 getter
      getType: function() {
        return this.multi == true ? 'checkbox' : 'radio'
      }
    },
    watch: {
      visible(v) {
        if (v) {
          this.getSelectdData().then(() => {
            if (this.activeKey == 'org') {
              this.queryDepartTree()
            } else {
              this.loadData()
            }
          })
        }
      },
      activeKey() {
        if (this.activeKey == 'org') {
          this.queryDepartTree()
        } else {
          this.loadData()
        }
      }
    },
    created() {
      // 该方法触发屏幕自适应
      this.resetScreenSize()
    },
    methods: {
      onPositionChange(record) {
        let data = this[this.activeKey + 'sData']
        if (record.mainPosition == 0) {
          for (let i = 0; i < data.length; i++) {
            if (data[i].positionCode != record.positionCode) {
              data[i].mainPosition = 1
            }
          }
        }
      },
      /**
       * 删除已选中商品
       * @param record
       */
      handleDelete(record) {
        this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
        this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
        this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
      },
      /**
       * 标签页的选中事件
       * @param name
       */
      tabClick(name) {
        this.activeKey = name
      },
      /**
       * 递归树结构数据，取出所有子元素
       * @param children
       * @param selected
       * @returns {*}
       */
      getAllChildren(children, selected) {
        if (children && children.length) {
          children.map(child => {
            selected.push(child)
            this.getAllChildren(child.children, selected)
          })
        }
        return selected
      },
      /**
       * 选中树节点操作
       * @param checkedKeys
       * @param checked 不等于undefined 表示当前事件为checkbox事件，否则为点击树节点事件
       * @param checkedNodes
       * @param node
       * @param event
       */
      handleCheckbox(checkedKeys, { checked, checkedNodes, node, event }) {
        if (checked !== undefined) {
          //todo 当事件为checkbox事件时，checkedKeys当前选中的数据包含自节点数据
          this.selectedKeys = checkedKeys
          this.categoryData = this.getAllChildren(this.treeData, []).filter(node => checkedKeys.includes(node.code)).map(node =>
            Object.assign({}, node, {
              children: null
            }))
        } else {
          //todo 当事件为nodeClick事件时，checkedKeys当前选中数据为当前点击节点
          const checkNodes = [node.dataRef, ...this.getAllChildren(node.dataRef.children, [])]
          //todo 如果当前点击节点已经被选中，则执行删除操作
          if (this.selectedKeys.includes(node.dataRef.code)) {
            checkNodes.map(node => {
              this.selectedKeys.remove(node.code)
              //todo 从右边table删除选中数据
              this.categoryData.remove(node)
            })
          } else {
            this.selectedKeys = Array.from(new Set(this.selectedKeys.concat(checkNodes.map(node => node.code))))
            //todo 添加选中数据到右边table
            this.categoryData = Array.from(new Set([...this.categoryData, ...checkNodes.map(node => Object.assign({}, node, {
              children: null
            }))]))
          }

        }
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth
        if (screenWidth < 500) {
          this.scrollTrigger = { x: 800 }
        } else {
          this.scrollTrigger = {}
        }
      },
      showModal(record) {
        this.userInfo = record
        this.visible = true
        this.form.resetFields()
      },
      /**
       * 获取查询参数
       * @returns {*}
       */
      getQueryParams() {
        let param = Object.assign({}, this.queryParam)
        param.current = this.ipagination.current
        param.size = this.ipagination.pageSize
        return filterObj(param)
      },
      searchReset(num) {
        let that = this
        if (num !== 0) {
          that.loadData(1)
        }
        that.selectedKeys = []
        that.categoryData = []
        that.rolesData = []
        that.roleSelectionRows = []
        that.roleSelectedRowKeys = []
        that.positionsData = []
        that.positionSelectionRows = []
        that.positionSelectedRowKeys = []
        that.activeKey = 'role'
      },
      close() {
        this.searchReset(0)
        this.visible = false
      },
      handleSubmit() {
        let that = this
        that.$emit('ok', {
          positions: that['positionsData'],
          roles: that['rolesData'],
          username: this.userInfo.userName
        })
        // that.searchReset(0)
        // that.close()
      },
      /**
       * 手动全选/取消全选分类
       * @param selected
       * @param selectedRows
       * @param changeRows
       */
      onSelectAll(selected, selectedRows, changeRows) {
        this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code'])
        this[this.activeKey + 'SelectionRows'] = selectedRows
        if (selected) {
          let data_ = this[this.activeKey + 'sData']
          //todo 选中
          changeRows.map(row => {
            let n = 0
            if (data_ != null && data_ != undefined) {
              // debugger
              for (let i = 0; i < data_.length; i++) {
                if (data_[i].mainPosition == 0) {
                  n = 1
                  break
                }
              }
              if (n == 1) {
                row.mainPosition = 1
              }
            }
            this[this.activeKey + 'sData'].push(row)
          })
        } else {
          //todo 取消选中
          changeRows.map(row => {
            this[this.activeKey + 'sData'].removeByCode(row, this.activeKey + 'Code')
          })
        }
      },
      onClickRow(record) {
        return {
          on: {
            click: () => {
              const keys = this[this.activeKey + 'SelectedRowKeys']
              if (keys.indexOf(record[this.activeKey + 'Code']) == -1) {
                keys.push(record[this.activeKey + 'Code'])
                // this[this.activeKey + 'SelectionRows'].push(record)
                this[this.activeKey + 'sData'].push(record)
                record.mainPosition = 1
                this.positionsData[0].mainPosition  = 0
              } else {
                keys.remove(record[this.activeKey + 'Code'])
                this[this.activeKey + 'SelectionRows'].remove(record)
                this[this.activeKey + 'sData'].splice(keys.indexOf(record[this.activeKey + 'Code']),1)
              }
              this[this.activeKey + 'SelectedRowKeys'] = keys
            }
          }
        }
      },
      /**
       * 手动勾选/取消分类
       * @param record
       * @param selected
       * @param selectedRows
       * @param nativeEvent
       */
      onSelect(record, selected, selectedRows, nativeEvent) {
        this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code'])
        this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
        if (selected) {
          //todo 选中
          let data_ = this[this.activeKey + 'sData']
          let n = 0
          if (data_ != null && data_ != undefined) {
            // debugger
            for (let i = 0; i < data_.length; i++) {
              if (data_[i].mainPosition == 0) {
                n = 1
                break
              }
            }
            if (n == 1) {
              record.mainPosition = 1
            }
          }
          this[this.activeKey + 'sData'].push({ ...record })
          if (data_ === this.positionsData && this.positionsData.length == 1){
            this.positionsData[0].mainPosition  = 0
          }
        } else {
          //todo 取消选中
          this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
        }
      },
      onSearch() {
        this.loadData(1)
      },

      /**
       * 覆盖mixin的loadData方法
       * @param arg
       * @returns {Promise<void>}
       */
      async loadData(arg) {
        let params = this.getQueryParams()//查询条件
        if (arg === 1) {
          this.ipagination.current = 1
        }
        let url
        if (this.activeKey === 'position') {
          url = '/cnPositionController/getNoPosPageList'
        }
        if (this.activeKey === 'role') {
          url = '/cnRoleController/getRoleList'
        }
        this.loading = true
        await postAction(url, { ...params }).then((res) => {
          console.log(res)
          if (res.success) {
            this[this.activeKey + 's'] =
              this.activeKey === 'role' ? res.result.records.map(row => Object.assign({}, row, {
                mainPosition: 0
              })) : res.result.records
            this.ipagination.total = res.result.total
          }
        }).finally(() => {
          this.loading = false
        })
      },
      /**
       * 获取已选中数据
       */
      getSelectdData() {
        const positionUrl = '/cnPositionController/getListByUsername'
        const roleUrl = '/cnRoleController/getRoleListByUsername'
        return Promise.all([
          getAction(roleUrl, { userName: this.userInfo.userName }),
          getAction(positionUrl, { username: this.userInfo.userName })
        ]).then(([roles, positions]) => {
          if (roles.success && roles.result && roles.result.length) {
            this['roleSelectedRowKeys'] = roles.result.map(row => row.roleCode)
            this['roleSelectionRows'] = roles.result
            this['rolesData'] = roles.result
          }
          if (positions.success && positions.result && positions.result.length) {
            this['positionSelectedRowKeys'] = positions.result.map(row => row.positionCode)
            this['positionSelectionRows'] = positions.result
            this['positionsData'] = positions.result
          }
        })
      },
      /**
       * 获取分类树
       * @returns {*}
       */
      queryDepartTree() {
        this.typeLoading = true
        return queryDepartTreeList().then((res) => {
          if (res.success) {
            this.treeData = this.handleStruct(res.result)
            // 默认展开父节点
            this.expandedKeys = this.treeData.map(item => item.code)
          }

          this.typeLoading = false
        }).catch(e => {
          this.$message.warning(res.message)
          this.typeLoading = false
        })
      },
      /**
       * 重构树结构数据
       * @param tree
       * @returns {*}
       */
      handleStruct(tree) {
        return tree.map(t => {
          const json = Object.assign({}, t, {
            code: t.orgCode,
            name: t.orgName,
            type: t.orgType
          })
          if (json.children) {
            json.children = this.handleStruct(json.children)
          }
          return json
        })
      },
      modalFormOk() {
        this.loadData()
      }
    }
  }
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>

